package kernel.stl;

import java.util.ArrayList;

/** Representa uma lista de segmentos de reta.
 *
 * @author George
 */
public class LineSegmentList {
    
    ArrayList list = new ArrayList();
    
    public LineSegmentList() {
   
    }
    
    public LineSegment getLineSegment(int index) {
        if (index < 0 || index >= list.size())
            throw new IndexOutOfBoundsException("Índice inválido");
        return (LineSegment)list.get(index);
    }
    
    public void addLineSegment(LineSegment lineSegment, double tolerance) {
        
        for (int i = 0; i < this.getLineSegmentCount() - 1; i++) {
            if (!this.getLineSegment(i).isConnectedToPoint2(this.getLineSegment(i + 1), tolerance)) {
                if (this.getLineSegment(i).getPoint2().equals(lineSegment.getPoint1(), tolerance)) {
                    this.list.add(i, lineSegment);
                    
                    if (this.getLineSegment(i).getPoint2().equals(this.getLineSegment(i + 1).getPoint2(), tolerance)) {
                        LineSegment l = this.getLineSegment(i + 1);
                        this.list.remove(i + 1);
                        this.list.add(i + 1, l.newInvertedLine());                        
                    }
                        
                    
                    return;
                }
                else if (this.getLineSegment(i).getPoint2().equals(lineSegment.getPoint2(), tolerance)) {
                    this.list.add(i, lineSegment.newInvertedLine());
                    
                    if (this.getLineSegment(i).getPoint2().equals(this.getLineSegment(i + 1).getPoint2(), tolerance)) {
                        LineSegment l = this.getLineSegment(i + 1);
                        this.list.remove(i + 1);
                        this.list.add(i + 1, l.newInvertedLine());                        
                    }
                    
                    return;
                }                
            }
        }
        
        list.add(lineSegment);
    }  
    
    public int getLineSegmentCount() {
        return list.size();
    }
    
    public void addLineSegmentList(LineSegmentList lineSegmentList, double tolerance) {
        for (int i = 0; i < lineSegmentList.getLineSegmentCount(); i ++) {
            this.addLineSegment(lineSegmentList.getLineSegment(i), tolerance);
        }       
    }
    

}
